@page "/qdetail/{Qid}"
@using System.Security.Claims
@using BootstrapBlazorApp.Server.Components.CustomComponent
@using BootstrapBlazorApp.Server.Service
@using COSXML.Model.Tag
<Layout IsPage="true">
    <Header>
        <HeaderComponent User="@user" Type="true" PageName="题目详情"></HeaderComponent>
    </Header>
    <Main>
        <div style="height: 90vh">
            <Split>
                <FirstPaneTemplate>
                    <Split IsVertical="true" Basis="@baseArea">
                        <FirstPaneTemplate>
                            <div>
                                <Tab IsBorderCard="true" OnClickTabItemAsync="clickTabItem">
                                    <TabItem Text="题目描述">
                                        <div style="display: flex">
                                            <div class="q-title">
                                                @question.Title
                                                @if (isStar)
                                                {
                                                    <i class="bi bi-star-fill" style="color: #f6d70e" @onclick="removeStar"></i>
                                                }
                                                else
                                                {
                                                    <i class="bi bi-star" style="color: #666666" @onclick="addStar"></i>
                                                }
                                            </div>
                                            <div style="display: flex;align-items: center">
                                                @if (@Staus)
                                                {
                                                    <span style="color: #555555;margin-right:5px ">已完成</span>
                                                    <i class="bi bi-check-circle" style="color: #28a745;"></i>
                                                }
                                                else
                                                {
                                                    <span style="color: #555555;margin-right: 5px">未完成</span>
                                                    <i class="bi bi-dash-circle"></i>
                                                }
                                            </div>
                                        </div>
                                        <div style="display: flex;margin-bottom: 15px">
                                            <div style="margin-right: 5px">
                                                <Tag Color="@setDifficultyColor(@question.Difficulty)">@question.Difficulty</Tag>
                                            </div>
                                            @foreach (var tag in question.Tag.Split('、'))
                                            {
                                                <div style="margin-right: 5px">
                                                    <Tag Color="Color.Info">@tag</Tag>
                                                </div>
                                            }
                                        </div>
                                        <div class="q-content">@question.Introduction</div>
                                    </TabItem>
                                    <TabItem Text="参考答案">
                                        <div class="q-content">@question.Answer</div>
                                    </TabItem>
                                    <TabItem Text="讨论区">
                                        @if (comment?.Count == 0)
                                        {
                                            <Empty Image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" Width="133" Text="暂无评论"   />
                                        }
                                        else
                                        {
                                            @foreach (var commentItem in comment)
                                            {
                                                <CommentComponent Comment="@commentItem" UserID="@user.Id" OnCommentDeleted="@OnCommentDeleted" />
                                            }
                                        }
                                        @*发送评论*@
                                        
                                        <div style="position: fixed; bottom: 20px; width: 47%; display: flex;">
                                            <BootstrapInput PlaceHolder="请输入评论" @bind-Value="@commentContent" ShowLabel="false"/>
                                            <button style="border-radius: 5px;height: 30px;width: 60px;border: #999999;margin-left: 10px" @onclick="SendComment">发送</button>
                                        </div>
                                    </TabItem>
                                </Tab>
                            </div>
                        </FirstPaneTemplate>

                        <SecondPaneTemplate>
                            <Tab IsCard="true">
                                <TabItem Text="AI评阅结果">
                                    @if (!Staus)
                                    {
                                    <div>暂无评阅结果</div>
                                    }
                                    else
                                    {
                                        <div style="margin:1% 0;height: 100%">
                                            <div style="display: flex;height: 100px;margin: 0 2% 1rem;">
                                                <div class="r-overall">
                                                    @answerDetail.OverallRemark
                                                </div>
                                                <div class="d-flex justify-content-between">
                                                    <Circle Value="@answerDetail.Score.Value" Color="@setScoreColor(answerDetail.Score.Value)" StrokeWidth="5" Width="100">
                                                        <div style="font-weight: bold;font-size: 30px;line-height: 1.5em">
                                                            @answerDetail.Score
                                                        </div>
                                                    </Circle>
                                                </div>
                                            </div>
                                            <div style="height:calc(100% - 125px);">
                                                <Card IsShadow="true" Color="Color.Secondary" HeaderText="评价详情" style="height: 100% !important;">
                                                    <BodyTemplate>
                                                        <Scroll Height="calc(100% - 10px)">
                                                            <div class="r-detail">
                                                                @answerDetail.DetailRemark
                                                            </div>
                                                        </Scroll>
                                                        
                                                    </BodyTemplate>
                                                </Card>
                                            </div>
                                            
                                        </div>
                                        
                                    }
                                </TabItem>
                            </Tab>
                        </SecondPaneTemplate>
                    </Split>
                </FirstPaneTemplate>
                
                <SecondPaneTemplate>
                    <Card HeaderText="我的回答" class="mt-3" style="margin-top: 0 !important;height: 90vh;">
                        <HeaderTemplate>
                            <div class="flex-fill">
                            </div>
                            <Select TValue="string" class="ms-1" style="width: 150px;margin-right: 1rem" @bind-value="@model">
                                <Options>
                                    <SelectOption Text="通义千问" Value="TongYi" />
                                    <SelectOption Text="KIMI" Value="Kimi" />
                                </Options>
                            </Select>
                            <Button IsOutline="true" Size="Size.Small" Color="Color.Primary" Icon="bi bi-cloud-upload" OnClick="@SubmitAnswer">提交</Button>
                        </HeaderTemplate>
                        <BodyTemplate>
                            <textarea @bind="@answerDetail.UserAnswer" class="a-textarea"></textarea>
                        </BodyTemplate>
                    </Card>
                </SecondPaneTemplate>
                
            </Split>
        </div>
    </Main>
</Layout>

@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject LlmChainService LlmChainService
@inject MessageService MessageService
@code {
    [Parameter]
    public string Qid { get; set; }
    
    public User user { get; set; }
    private ClaimsPrincipal? _user;
    
    private Question question { get; set; }
    private bool Staus { get; set; }
    private string baseArea="30%";
    private AnswerDetail? answerDetail { get; set; }
    private string commentContent;
    
    private List <Comment> comment = [];
    private User users=new();
    private Comment newComment = new();
    
    private bool isStar = false;

    private string model = "TongYi";
    
    protected override async Task OnInitializedAsync()
    {
        base.OnInitialized();
        //获得用户信息
        _user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
        
        if (_user == null)
        {
            return;
        }

        var value = _user.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        if (value != null)
        {
            var user_id = int.Parse(value);
            user = User.Find(user_id);
        }

        //获得题目信息
        int qid = Convert.ToInt32(Qid);
        //查询数据库获得题目详细信息
        question=Question.Where(q=>q.Id==qid).First();
        answerDetail = AnswerDetail.Where(q => q.QuestionId == qid&&q.UserId==user.Id).First();
        if (answerDetail == null)
        {
            Staus = false;
            answerDetail = new AnswerDetail();
            answerDetail.UserId=user.Id;
            answerDetail.QuestionId=Convert.ToInt32(Qid);
        }
        else
        {
            Staus = true;
        }
        //是否收藏
        isStar=StarList.Where(s=>s.QuestionID==qid&&s.UserID==user.Id).Count()>0;
        //获得评论信息
        comment = Comment.Where(q => q.QuestionID == qid).ToList();
        newComment.Content = "";
    }
    private Color setDifficultyColor(string dif)
    {
        return dif switch
        {
            "简单" => Color.Success,
            "中等" => Color.Warning,
            "困难" => Color.Danger,
            _ => Color.Dark
        };
    }
    private Color setScoreColor(int score)
    {
        return score switch
        {
            <= 30 => Color.Danger,
            <= 60 => Color.Warning,
            _ => Color.Success
        };
    }

    private async Task SubmitAnswer()
    {
        //调用大模型进行评价
        //获得score,overallremark,detailremark三个参数
        var scoreChainAsync = await LlmChainService.ScoreChainAsync(question.Title,answerDetail.UserAnswer,question.Answer,model);
        answerDetail.Score = Convert.ToInt32(scoreChainAsync["score"]);//得分
        answerDetail.OverallRemark = scoreChainAsync["comment"];//总评
        Staus = true;//完成状态
        await Task.Delay(10);
        
        await MessageService.Show(new MessageOption()
        {
            Content = "评阅完成"
        });
        
        StateHasChanged();

        //如果得分过低，自动加入收藏
        if (answerDetail.Score < 60)
        {
            addStar();
        }
        
        //同步到数据库
        answerDetail.DetailRemark= "";//先清空
        await foreach (var se in LlmChainService.DetailChainStream(question.Title, answerDetail.UserAnswer, question.Answer, scoreChainAsync))
        {
            answerDetail.DetailRemark += se;
            StateHasChanged();
        }
        answerDetail.Save();//保存
    }

    private Task clickTabItem(TabItem item)
    {
        baseArea = item.Text is "讨论区" or "参考答案" ? "100%" : "30%";
        StateHasChanged();
        return Task.CompletedTask;
        
    }
    
    private void SendComment(){
        newComment.QuestionID = Convert.ToInt32(Qid);
        newComment.UserID = user.Id;
        newComment.Content = commentContent;
        newComment.Save();

        // 清空输入框
        commentContent = "";
        StateHasChanged();
        OnInitializedAsync();
    }

    private void OnCommentDeleted(Comment comment)
    {
        comment.Delete();
        StateHasChanged();
        OnInitializedAsync();
    }

    private void addStar()
    {
        var s = new StarList
        {
            QuestionID = Convert.ToInt32(Qid),
            UserID = user.Id
        };
        s.Insert();
        isStar=!isStar;
        StateHasChanged();
    }

    private void removeStar()
    {
        var s=StarList.Where(ss=>ss.QuestionID==Convert.ToInt32(Qid)&&ss.UserID==user.Id).First();
        if (s == null) return;
        s.Delete();
        isStar=!isStar;
        StateHasChanged();
    }
}
